function parse(str){
	console.log(str);
	var jsonObj=window.JSON.parse(str);
	var type=jsonObj["type"];
	var showObj=$(jsonObj['showObj']);
	var retCode=$(jsonObj['retCode']);
	if(type==1){
		loginType(jsonObj);
	}else if(type==2){
		if(retCode=1){
			//根据from ID 获取 from Name
			//先从pInfo处获取如果form ID等于当前登录用户，则说明是系统返回的消息
			//form ID不等于当前用户，则从好友列表中获取信息
			var from=jsonObj["from"];
			var method=jsonObj["method"];
			var msgTime=jsonObj["timestamp"];
			var msg=jsonObj["message"];
			var fromName="";
			if($("#pInfo").attr("loginPid")==from){
				fromName=$("#pName").find("#nameSpan").text();
				if(method=='shake'){
					msg="您"+msg;
					showObj.parent().effect('shake',{},200,function(){});
				}
				var msgHtml="<div class='selfInfo'>"+fromName+" &nbsp;"+mill2Time(msgTime,'HH:mm:ss')+"</div><div class='showMsg'>"+msg+"</div>";
				msgHtml+='<div id="msg_end"	style="height:0px; overflow:hidden;margin-top:2px;"></div>';
				showObj.find(".msgShowArea").find("#msg_end").remove();
				showObj.find(".msgShowArea").append($(msgHtml));
//				document.getElementById("msg_end").scrollIntoView(); 
				showObj.find(".msgShowArea").find("#msg_end").get(0).scrollIntoView(true); 
			}else{
				if($("#"+from).length==0){//如果是陌生人，不存在于好友列表中，则alert();
					alert(from +" send msg :"+msg);
					alert("温馨提示:别跟陌生人说话!");
					return;
				}
				fromName=$("#"+from).find("span.fName").text();
				if(method=='shake'){
					msg=fromName+"向您"+msg;
				}
				
				if($("#Dialog-"+from).length==0){//如果没有弹出窗口,两种情况：1好友列表未展开，2好友列表已展开
					//如果好友列表未打开，则闪烁好友列表
					if(!$("#"+from).is(":visible")){
						var thisGroup=$("#"+from).parent().prev().find(".groupName");
						clearGroupInterval(thisGroup);
						setGroupInterval(thisGroup);
					}
					//$("#"+from)头像闪动
					//先清除已有的定时任务
					clearFHeadInterval($("#"+from));
					//来消息时无弹窗，则闪烁好友列表中的头像，且将消息存储到消息盒子中
					setFHeadInterval($("#"+from));
					msgBox.receiveMsg(from,fromName,msgTime,msg);//消息盒子接受消息
				}else if($("#Dialog-"+from).length>0){
					if(method=='shake'){
						$("#Dialog-"+from).parent().effect('shake',{},200,function(){});//抖动
					}
					var maxIndex = 0;
					for ( var i = 0; i < dialogArr.length; i++) {
						if (dialogArr[i] != null) {
							var zIndex = dialogArr[i].css("z-index");
							maxIndex = (maxIndex <= zIndex ? zIndex
									: maxIndex);
						}
					}//获取窗口最上层的z-index
					if(maxIndex>$("#Dialog-"+from).parent().css("z-index")){//说明当前聊天窗口不在最上层
						//获取对话框对应的任务栏,加上定时闪烁功能
						var taskID=$("#Dialog-"+from).attr("dialogindex");
						clearTaskBarInterval(taskID);//先清除定时任务
						setTaskBarInterval(taskID);//再新建定时任务
					}
					
					//如果窗口是在最上层，则直接显示数据，不需要任务栏处闪烁
					fromName=$("#"+from).find("span.fName").text();
					var msgHtml="<div class='fromInfo'>"+fromName+" &nbsp;"+mill2Time(msgTime,'HH:mm:ss')+"</div><div class='showMsg'>"+msg+"</div>";
					msgHtml+='<div id="msg_end"	style="height:0px; overflow:hidden"></div>';
					$("#Dialog-"+from).find(".msgShowArea").find("#msg_end").remove();
					$("#Dialog-"+from).find(".msgShowArea").append($(msgHtml));
//					document.getElementById("msg_end").scrollIntoView(); 
					$("#Dialog-"+from).find(".msgShowArea").find("#msg_end").get(0).scrollIntoView(); 
				}
			}
			
		}else {
			//showObj.find(".msgShowArea").text(jsonObj['ret']);
		}
	}else
		if(type==3){
			var method=jsonObj["method"];
			if(method=='upload'||method=='talk'){
				if(jsonObj['state']=='ready'){//如果服务器访问的状态为ready，则可以上传文件数据
					if(jsonObj['showType']=='display'){//如果是1M以下的图片则直接上传文件
						var uploadReader=new FileReader();
						uploadReader.readAsArrayBuffer(uploadFile);
						uploadReader.onloadend = function loaded(evt) {
							binaryString = evt.target.result;
							socket.send(binaryString);
						};
					}else if(jsonObj['showType']=='rightWin'){//非图片文件或大于1M的图片文件，则分块上传，且在右侧窗口显示进度条，此处需新增一个websocket
						
					}
				}else if(jsonObj['state']=='success') {
					var filePath=jsonObj['filePath'].replace("MyWebQQ/","");
					showObj.find(".msgSendArea").find(".msgDiv").find(".loadingImg").remove();//移除等待加载的标识图片
					var img = '<img class="preview" src="'+filePath+'"/>';
					$(img).appendTo(showObj.find(".msgSendArea").find(".msgDiv"));
				}
			}else if(method=='deliver'){
				if(jsonObj['state']=='ready'){//如果服务器访问的状态为ready，则可以上传文件数据
					var uploadReader=new FileReader();
					uploadReader.readAsArrayBuffer(uploadFile);
					uploadReader.onloadend = function loaded(evt) {
						binaryString = evt.target.result;
						socket.send(binaryString);
					};
				}else if(jsonObj['state']=='success') {
					var filePath=jsonObj['filePath'].replace("MyWebQQ/","");
					showObj.find(".msgSendArea").find(".msgDiv").find(".loadingImg").remove();//移除等待加载的标识图片
					var img = '<img class="preview" src="'+filePath+'"/>';
					$(img).appendTo(showObj.find(".msgSendArea").find(".msgDiv"));
				}
//				var from=jsonObj['showObj'];
//				if($(from).length>0){//接收方显示消息判断对方是否接受了消息
//					
//				}else{//对方接受消息，可选择是否接受文件
//					if($("#Dialog-"+jsonObj['from']).length>0){//如果接收文件方聊天窗口已打开
//						var rightWinObj=$("#Dialog-"+jsonObj['from']).find(".rightWin");
//						fileDelivery(rightWinObj,jsonObj,null,'receive');
//					}else{//通知消息
//						
//					}
//				}
			}
	}
}



function loginType(jsonObj){
	
	var method=jsonObj["method"];
	var showObj=$(jsonObj['showObj']);
	var retMsg=jsonObj["ret"];
	var retCode=jsonObj["retCode"];
	var pid=jsonObj["pid"];
	
	if('getValidCode'==method){//获取验证码
		showObj.text(retMsg);
	}
	if("login"==method){
		if(retCode==1){
			var people=jsonObj["people"];
			var groups=people["groups"];
			var pName=people["pname"];
			var pSay=people["psay"];
			showObj.dialog("destroy");//隐藏登陆框
			$("#loginDialog").dialog("destroy");
			$("#IMBar").find("#pInfo").attr("loginPid",pid).find("#pName").find("#nameSpan").text(pName);
			$("#IMBar").find("#pInfo").attr("loginPid",pid).find("#pSay").text(pSay).attr("title",pSay);
			openDialog($("#IMBar"),"","Talk One",280,500,'talk');
			$("#imContacts").tabs().css({"min-width":280});
			$(".imtab").css({
				width:'100%',
				height:$("#IMBar").height()-100-40-39,
				"overflow":"auto",
				position:"relative"
			});
			$("#pHeader img").hover(function(){
				$(this).toggleClass('hover');
			},function(){
				$(this).toggleClass('hover');
			});
			$("#IMBar").unbind("dialogresize").bind( "dialogresize", function(event, ui) {
				var dialogWid=$(this).parent().css("width").replace("px","");
				if(dialogWid<=280){
					$(this).dialog("option","width",280);//限制最小宽度
				}
				$(".imtab").css({
					width:'100%',
					height:$("#IMBar").height()-100-40-39,
					"overflow":"auto",
					position:"relative"
				});
			});
			$("#friendGroups").html("");
			for(var i=0;i<groups.length;i++){
				var groupObj=groups[i];
				var friends=groupObj["gfriends"];
				var groupHtml='<div class="friendGroup" id="'+groupObj['id']+'" state="close"><span class="ui-icon ui-icon-triangle-1-e"  style="display:inline-block;"></span><span class="groupName" style="display:inline-block;">'+groupObj['gname']+'('+groupObj['gonlinecounts']+'/'+groupObj['gcounts']+')</span></div>';
				groupHtml+="<div class='friends' style='display:none;'>";
				for(var j=0;j<friends.length;j++){
					var friend=friends[j];
					groupHtml+="<div class='friend' id='"+friend['pid']+"'>"+
					"<div class='fHeader'><img alt='' src='./appImages/"+friend['pheader']+"'>"+
					"</div>"+
					"<div class='fState'>"+
						"<span class='fName'>"+friend['pname']+"</span><span class='fNameMark'>("+friend['uname']+")</span>"+
						"<p class='fSay' title='"+friend['psay']+"'>"+friend['psay']+"</p>"+
					"</div>"+
					"</div>";
				}
				groupHtml+="</div>";
				$(groupHtml).appendTo($("#friendGroups")).unbind("click").bind('click',function(){
					var obj=$(this);
					if(obj.attr('state')=='close'){
						obj.find("span.ui-icon").attr("class","ui-icon ui-icon-triangle-1-s");
						obj.attr("state","open");
						obj.next(".friends").show();
						//展开式如果有分组闪烁，则清除定时任务
						var thisGroup=obj.find(".groupName");
						clearGroupInterval(thisGroup);
						
						$(".friend").unbind('hover').bind('hover',function(){
							$(this).toggleClass("friendHover");
						},function(){
							$(this).toggleClass("friendHover");
						});
						$(".friend").unbind("dblclick").bind('dblclick',function(){
							var friendObj=$(this);
							//先清除闪烁效果
							clearFHeadInterval(friendObj);
							//设置talkWindow的对端联系人信息
							$("#talkWindow").find(".topWin").find(".talkPInfo").find(".talkPName").text(friendObj.find(".fName").text());
							$("#talkWindow").find(".topWin").find(".talkPInfo").find(".talkPSay").text(friendObj.find(".fSay").text());
							openDialog(friendObj,"",friendObj.find(".fName").text(),540,510,'talkWindow');
							var fromName=friendObj.find(".fName").text();
							var fromId=friendObj.attr('id');
							var openedDia=$("#Dialog-"+friendObj.attr('id'));
							
//							openedDia.find(".leftWin").css({
//								width:openedDia.width()-MIDDLE_WIN_WIDTH-DEFAULT_RIGHT_WINDOW_WIDTH//7为收缩条宽度，150为默认面板宽度，默认面板显示双方的个人资料
//							}).find(".msgShowArea").css({
//								height:openedDia.height()-DEFAULT_RIGHT_WINDOW_WIDTH
//							});
//							openedDia.find(".rightWin").css({
//								height:openedDia.height()
//							});
							
							openedDia
							.find(".middleWin").css({
								height:openedDia.height()
							})
							.hover(function(){
								if($(this).attr('state')!='open'){
									$(this).removeClass("middleOpenWinHover");
									$(this).addClass("middleWinHover");
								}else{
									$(this).removeClass("middleWinHover");
									$(this).addClass("middleOpenWinHover");
								}
							},function(){
								$(this).removeClass("middleWinHover");
								$(this).removeClass("middleOpenWinHover");
							}).click(function(){
								var midObj=$(this);
								//判断当前右侧窗口是何种类型的窗口，default为双方信息展示窗口，other为其他窗口，如传送文件，历史消息，等等
								var rightWidth=openedDia.find(".rightWin").attr("type")=='default'?DEFAULT_RIGHT_WINDOW_WIDTH:OTHER_RIGHT_WINDOW_WIDTH;
								if(midObj.attr('state')!='open'){
									openedDia.dialog("option","width", openedDia.width()+rightWidth );
									openedDia.css({
										height:midObj.height()
									});
									openedDia.find(".rightWin").css({
										height:midObj.height()
									}).show();
									midObj.attr("state","open");
									midObj.removeClass("middleWinHover");
									midObj.addClass("middleOpenWinHover");
								}else{
									openedDia.dialog( "option", "width", openedDia.width()-rightWidth );
									openedDia.css({
										height:midObj.height()
									});
									openedDia.find(".rightWin").hide();
									midObj.attr("state","close");
									midObj.removeClass("middleOpenWinHover");
									midObj.addClass("middleWinHover");
								}
								
							});
							talkWindowResize(openedDia);
							
							//先从消息备份中查看是否有未接受信息
							//需要将消息全部发送给打开的窗口
							if(msgBoxObj.find("#msg-from-"+fromId).length>0){
								var allMsg=msgBoxObj.find("#msg-from-"+fromId).find(".msg");
								for(var i=0;i<allMsg.length;i++){
									var msgObjTmp=allMsg[i];
									var msgHtml="<div class='fromInfo'>"+fromName+" &nbsp;"+$(msgObjTmp).find(".msgTime").text()+"</div><div class='showMsg'>"+$(msgObjTmp).find(".msgContent").html()+"</div>";
									msgHtml+='<div id="msg_end"	style="height:0px; overflow:hidden"></div>';
									openedDia.find(".msgShowArea").find("#msg_end").remove();
									openedDia.find(".msgShowArea").append($(msgHtml));
									openedDia.find(".msgShowArea").find("#msg_end").get(0).scrollIntoView(); 
								}
								//移除消息的备份存储和提醒
								msgBox.removeMessageByFrom(fromId);
							}
							
							//绑定聊天窗口的按钮事件
							openedDiaBtnClickEventBind(openedDia);
							uploadImage(openedDia.find(".msgSendArea").find(".msgDiv"));
							openedDia.find(".msgSendArea").find(".msgDiv").unbind('keydown').bind('keydown',function(event){//keyDown键盘事件
								if(event.keyCode==13){
									var fromPid=$("#pInfo").attr("loginPid");
									var jstr={};
									jstr.type=2;
									jstr.method="send";
									jstr.from=fromPid;
									jstr.to=friendObj.attr('id');
									jstr.showObj="#Dialog-"+friendObj.attr('id');
									jstr.timestamp=new Date().getTime();
									jstr.message=openedDia.find(".msgSendArea").find(".msgDiv").parent().html();
									socket.send(JSON.stringify(jstr));
									openedDia.find(".msgSendArea").find(".msgDiv").html("");
									return false;
								}
							});
							
							openedDia.find(".btnArea").find(".sendMsgBtn").unbind('click').bind('click',function(){
								var fromPid=$("#pInfo").attr("loginPid");
								var jstr={};
								jstr.type=2;
								jstr.method="send";
								jstr.from=fromPid;
								jstr.to=friendObj.attr('id');
								jstr.showObj="#Dialog-"+friendObj.attr('id');
								jstr.timestamp=new Date().getTime();
								jstr.message=openedDia.find(".msgSendArea").find(".msgDiv").parent().html();
								console.log(JSON.stringify(jstr));
								console.log(socket);
								socket.send(JSON.stringify(jstr));
								openedDia.find(".msgSendArea").find(".msgDiv").html("");
							});
							openedDia.unbind("dialogresize").bind( "dialogresize", function(event, ui) {
								talkWindowResize(openedDia);
							});
						});
					}else{
						obj.find("span.ui-icon").attr("class","ui-icon ui-icon-triangle-1-e");
						obj.attr("state","close");
						obj.next(".friends").hide();
					}
				});
			}
		}else{
			alert(retMsg);
			return false;
		}
	}
	
}


/**
 * rgb颜色值转16进制
 * @param rgb
 * @returns
 */
function rgb2hex(rgb){
	 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
	 return (rgb && rgb.length === 4) ? "#" +
	  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
	  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
	  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function openedDiaBtnClickEventBind(openedDia){
	//消息显示区DIV
	var showAreaObj=openedDia.find(".msgShowArea");
	//消息按钮区DIV
	var btnAreaObj=openedDia.find(".msgBtnArea");
	//消息编辑区DIV
	var sendAreaObj=openedDia.find(".msgSendArea").find(".msgDiv");
	//当前聊天窗口人的id
	var talkId=openedDia.attr("id").replace("Dialog-","");
	//按钮滑动效果
	btnAreaObj.find("div").unbind('hover').bind('hover',function(){
		$(this).toggleClass("btnHover");
	},function(){
		$(this).toggleClass("btnHover");
	}); 
	//抖动按钮
	btnAreaObj.find(".shakeBtn").unbind('click').bind('click',function(){
		var fromPid=$("#pInfo").attr("loginPid");
		var jstr={};
		jstr.type=2;
		jstr.method="shake";
		jstr.from=fromPid;
		jstr.to=talkId;
		jstr.showObj="#"+openedDia.attr('id');
		jstr.timestamp=new Date().getTime();
		jstr.message="发送了一个窗口抖动。";
		socket.send(JSON.stringify(jstr));
	});
	//清屏按钮
	btnAreaObj.find(".clearBtn").unbind('click').bind('click',function(){
		showAreaObj.html("");
	});
	//字体按钮
	btnAreaObj.find(".fontBtn").unbind('click').bind('click',function(){
		var fontSettingObj=$("#fontSettingBar-"+talkId);
		if(fontSettingObj.length<=0){//如果字体设置窗口不存在，则新加字体窗口，
			var fontHtml=$("#fontSetting").html();
			btnAreaObj.before(fontHtml);
			openedDia.find(".fontSettingBar").attr("id","fontSettingBar-"+talkId).show();
			fontSettingObj=$("#fontSettingBar-"+talkId);
		}else{
			fontSettingObj.toggle();
		}
		fontSettingObj.find(".fontBoldBtn").unbind('click').bind('click',function(){//字体加粗按钮绑定事件
			if($(this).attr("state")=='normal'){
				sendAreaObj.css({
					"font-weight":"bold"
				});
				$(this).attr("state","bold");
			}else{
				sendAreaObj.css({
					"font-weight":"normal"
				});
				$(this).attr("state","normal");
			}
		});
		fontSettingObj.find(".fontItalicBtn").unbind('click').bind('click',function(){//字体倾斜按钮绑定事件
			if($(this).attr("state")=='normal'){
				sendAreaObj.css({
					"font-style": "italic"
				});
				$(this).attr("state","italic");
			}else{
				sendAreaObj.css({
					"font-style":"normal"
				});
				$(this).attr("state","normal");
			}
		});
		fontSettingObj.find(".fontUnderlineBtn").unbind('click').bind('click',function(){//字体加下划线按钮绑定事件
			if($(this).attr("state")=='none'){
				sendAreaObj.css({
					"text-decoration": "underline"
				});
				$(this).attr("state","underline");
			}else{
				sendAreaObj.css({
					"text-decoration":"none"
				});
				$(this).attr("state","none");
			}
		});
		fontSettingObj.find(".fontFamily").unbind('change').bind('change',function(){//字体下拉框绑定事件
			sendAreaObj.css({
				"font-family": $(this).val()
			});
		});
		fontSettingObj.find(".fontSize").unbind('change').bind('change',function(){//字体大小下拉框绑定事件
			sendAreaObj.css({
				"font-size": $(this).val()+"pt"
			});
		});
		fontSettingObj.find(".fontColorBtn").unbind('click').bind('click',function(){//字体颜色按钮绑定事件
			var colorPanle=$(this).next("ul");
			var obj=$(this);
			colorPanle.show().find("li a").unbind('click').bind('click',function(){
				var textColor=$(this).find("span").css("backgroundColor");
				sendAreaObj.css({
					"color": rgb2hex(textColor)
				});
			});
			$(document).click(function(event){//隐藏取色器面板
				if(obj.attr("class")!=$(event.target).attr("class")){
					colorPanle.hide();
				}
			});
		});
	});
	//表情按钮
	btnAreaObj.find(".faceBtn").unbind('click').bind('click',function(){//表情按钮绑定事件
		var facePanle=$("#facePanel");//表情面板
		var obj=$(this);
		facePanle.appendTo($("body")).show().css({
			left:obj.offset().left-100,
			top:obj.offset().top-204,
			"z-index":openedDia.parent().css("z-index")+1
		});
		facePanle.find("a").hover(function(){//鼠标滑过效果
			$(this).css({
				height: "27px",
		    	border:"1px solid #008000",
		    	width: "27px"
			});
		},function(){
			$(this).css({
				height: "28px",
		    	border:"0px solid #008000",
		    	width: "28px"
			});
		}).unbind('click').bind('click',function(){//点击表情，输入框中插入表情
			var imgHtml="<img class='faceImg'></img>";
			$(imgHtml).attr("src","./style/images/face/"+$(this).attr("facecode")+".gif").appendTo(sendAreaObj);
		});
		$(document).click(function(event){//隐藏表情面板
			if(obj.attr("class")!=$(event.target).attr("class")){
				facePanle.hide();
			}
		});
	});
	//图片按钮
	btnAreaObj.find(".imageBtn").find("#imageFile").unbind('change').bind('change',function(){//选择文件上传时事件
		var obj=$(this);
		var files=obj[0].files;
		selectFile(sendAreaObj,talkId,files);
	});
	
}
